//  NewAnalysisViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/11/23.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit

class NewAnalysisViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {
    
    var father: NewAnalysisContainerViewController?
    
    var companys: [JSON] = []
    var selectedCompany: JSON?
    
    let datePicker = UIDatePicker.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 220))
    
    let dateField = UITextField()
    
    @IBOutlet weak var planIncomeLabel: UILabel!
    
    @IBOutlet weak var planCostLabel: UILabel!
    
    @IBOutlet weak var planProfit: UILabel!
    
    @IBOutlet weak var executeIncomeLabel: UILabel!
    
    @IBOutlet weak var executeCostLabel: UILabel!
    
    @IBOutlet weak var executeProfitLabel: UILabel!
    
    var firstSectionSource: [JSON] = []
    
    var secondSectionSource: [JSON] = []
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return firstSectionSource.count
        default:
            return secondSectionSource.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StasticCell") as! NewStasticCell
        switch indexPath.section {
        case 0:
            cell.model = firstSectionSource[indexPath.row]
            break
        case 1:
            cell.model = secondSectionSource[indexPath.row]
            break
        default:
            break
        }
        return cell
    }

    @IBOutlet weak var tableView: UITableView!
    
    var rowunitsintable: CGFloat{
        get{
            return CGFloat(2.6) + CGFloat((self.tableView(tableView, numberOfRowsInSection: 0) + self.tableView(tableView, numberOfRowsInSection: 1)))
        }
    }
    
    var averagerowheight: CGFloat{
        get{
            let contentheight = tableView.height - (tableView.tableHeaderView?.height ?? 0)
            return (contentheight - 10) / self.rowunitsintable
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return averagerowheight
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return averagerowheight * 0.8
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 10
        default:
            return averagerowheight
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 1:
            
            let v = UIView()
            
            let stackView = UIStackView.init(frame: CGRect.init(origin: CGPoint(x: 0, y: 0), size: CGSize(width: UIScreen.main.bounds.size.width, height: averagerowheight)))
            
            stackView.axis = .horizontal
            
            stackView.alignment = .fill
            
            stackView.distribution = .fillEqually
            
            v.backgroundColor = UIColor.white
            
            v.addSubview(stackView)
            
            let total = secondSectionSource.reduce(0) { (result, json) -> Int in
                return (json.contents?["sum"]?.int ?? 0) / 1000000 + result
            }

            let totalmonth = secondSectionSource.reduce(0) { (result, json) -> Int in
                return (json.contents?["toMonth"]?.int ?? 0) / 1000000 + result
            }

            let totalstr = String(total).rmbformat

            let dynamic = secondSectionSource.reduce(0) { (result, json) -> Int in
                return (json.contents?["toDay"]?.int ?? 0) / 1000000 + result
            }
            
            let dynamicstr =  String(dynamic).rmbformat
            let totalMonthStr = String(totalmonth).rmbformat
            let titles = ["合计",dynamicstr,totalMonthStr,totalstr]
            for title in titles {
                let label = UILabel.init()
                label.width = title.size(with: UIFont.systemFont(ofSize: 14)).width
                label.height = title.size(with: UIFont.systemFont(ofSize: 14)).height
                label.text = title
                label.font = UIFont.systemFont(ofSize: 14)
                label.textAlignment = .center
                stackView.addArrangedSubview(label)
            }
            let line = UIView()
            line.backgroundColor = tableView.separatorColor
            line.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: self.view.width, height: 0.5))
            v.addSubview(line)
            return v
        default:
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    var cbtitles = ["成本","当日动态","当月动态","当年累计"]
    var srtitles = ["收入","当日动态","当月动态","当年累计"]
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        let height = averagerowheight * 0.8
        view.frame = CGRect.init(origin: CGPoint.zero, size: CGSize(width: self.view.width, height: height))
        let stackView = UIStackView.init()
        stackView.axis = .horizontal
        stackView.alignment = .fill
        stackView.distribution = .fillEqually
        view.backgroundColor = UIColor.hex("FFF8E6")
        view.addSubview(stackView)
        stackView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        let titles = section == 0 ? srtitles : cbtitles
        for title in titles {
            let label = UILabel.init()
            label.textColor = UIColor.hex("2785FF")
            label.width = title.size(with: UIFont.systemFont(ofSize: 14)).width
            label.height = title.size(with: UIFont.systemFont(ofSize: 14)).height
            label.text = title
            label.font = UIFont.systemFont(ofSize: 14)
            label.textAlignment = .center
            stackView.addArrangedSubview(label)
        }
        return view
    }
    
    var selectedDate: String {
        get{
            return datePicker.date.dateLineStr
        }
    }
    
    @IBAction func showOrganizations(_ sender: Any) {
        self.popalert()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.separatorInset = .zero
        self.navigationItem.rightBarButtonItem?.tintColor = UIColor.white
        let nib = UINib.init(nibName: "NewStasticCell", bundle: Bundle.main)
        tableView.register(nib, forCellReuseIdentifier: "StasticCell")
        tableView.tableFooterView = UIView()
        calendarBtn.titleLabel?.textAlignment = .center
        calendarBtn.setTitle(Date.init().dateLineStr.replacingOccurrences(of: "-", with: " ", options: .literal, range: Range.init(NSRange.init(location: 0, length: 5), in: Date.init().dateLineStr)), for: .normal)
        refreshimg(date: Date())
        self.calendarView.removeFromSuperview()
        let bar = self.father!.navigationController!.navigationBar
        bar.addSubview(self.calendarView)
        self.calendarView.tag = 10001
        datePicker.locale = Locale.init(identifier: "zh_CN")
        datePicker.backgroundColor = .white
        datePicker.datePickerMode = .date
        datePicker.date = Date()
        dateField.delegate = self
        datePicker.maximumDate = Date()
        let window = self.father!.view
        window?.addSubview(dateField)
        dateField.inputView = datePicker
        dateField.inputAccessoryView = self.toolbarview
        self.calendarView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-20)
            make.width.equalTo(30)
            make.height.equalTo(30)
            make.centerY.equalToSuperview()
        }
        self.load(with: "GETORG")
    }
    
    @IBOutlet weak var calendarView: UIView!
    
    @IBOutlet weak var calendarBtn: UIButton!
    @IBAction func showDateAction(_ sender: Any) {
        selectedIndex = 3
        dateField.becomeFirstResponder()
    }
    
    func refreshimg(date: Date)->Void{
        
    }
    
    override func canceledit() {
        super.canceledit()
        self.dateField.resignFirstResponder()
    }
    
    override func pop() {
        self.dateField.resignFirstResponder()
        super.pop()
    }
    
    override func endedit() {
        
        let date = datePicker.date
        calendarBtn.setTitle(date.dateLineStr.replacingOccurrences(of: "-", with: " ", options: .literal, range: Range.init(NSRange.init(location: 0, length: 5), in: date.dateLineStr)), for: .normal)
        srtitles = ["收入","当日动态","当月动态","当年累计"]
        cbtitles = ["支出","当日动态","当月动态","当年累计"]
        self.tableView.reloadData()
        NotificationCenter.default.post(name: NSNotification.Name("RfhDate"), object: date)
        self.load(with: "GETORG")//自己
        
        
        
        NotificationCenter.default.post(name: NSNotification.Name("DateChange"), object: nil)
        
        
        self.dateField.resignFirstResponder()
        self.view.endEditing(true)
    }
    
    var selectedIndex = 0
    
    @IBAction func changeTime(_ sender: UISegmentedControl) {
        selectedIndex = sender.selectedSegmentIndex
        srtitles = ["收入","当日动态","当月动态","当年累计"]
        cbtitles = ["支出","当日动态","当月动态","当年累计"]
        self.tableView.reloadData()
        self.load(with: "GETORG")
    }
    
    @IBOutlet weak var companyField: UILabel!
    
    override var names: Array<String>{
        get{
            return ["GETORG","Total","List","JIIncomes","JYYSK"]
        }
    }
    
    override func path(for name: String) -> String {
        switch name {
        case "GETORG":
            return GETORG
        case "Total":
            return JYDatas
        case "List":
            return JYCosts
        case "JYYSK":
            return JYYSK
        default:
            return JYIncomes
        }
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        switch name {
        case "GETORG":
            return [:]
        case "Total":
            if let orgCode = selectedCompany?.contents?["code"]?.rawString() {
                return ["orgCode":orgCode,"endDate": selectedDate]
            } else {
                return ["orgCode":""]
            }
        case "List":
            if let orgCode = selectedCompany?.contents?["code"]?.rawString() {
                return ["orgCode":orgCode,"endDate": selectedDate]
            } else {
                return ["orgCode":""]
            }
        case "JYYSK":
            if let orgCode = selectedCompany?.contents?["code"]?.rawString() {
                return ["orgCode":orgCode,"searchDate":selectedDate]
            } else {
                return ["orgCode":""]
            }
        default:
            if let orgCode = selectedCompany?.contents?["code"]?.rawString() {
                return ["orgCode":orgCode,"endDate":selectedDate]
            } else {
                return [:]
            }
        }
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    override func success(for name: String) -> NetSuccess {
        
        func org(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    companys = data
                    if companys.count > 0 {
        
                        let item = companys[0]
                        
                        selectedCompany = item
                        
                        self.companyField.text = item.contents?["name"]?.rawString()
                        
                        self.load(with: "Total")
                        
                        self.load(with: "List")
                        
                        self.load(with: "JIIncomes")
                        
                        self.load(with: "JYYSK")
                    }
                    
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        func total(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.contents {
                    if let operatingIncome = data["operatingIncome"]?.int {
                        executeIncomeLabel.text = String(operatingIncome / 1000000).rmbformat
                        if let planCost = data["operatingCost"]?.int {
                            
                            executeCostLabel.text = String(planCost / 1000000).rmbformat
                            
                            executeProfitLabel.text = String((operatingIncome - planCost) / 1000000).rmbformat
                        }
                    }
                    
                    if let income = data["planIncome"]?.int {
                         planIncomeLabel.text = String(income / 1000000).rmbformat
                        if let cost = data["planCost"]?.int {
                            planCostLabel.text = String(cost / 1000000).rmbformat
                            let profit = (income - cost) / 1000000
                            planProfit.text = String(profit).rmbformat
                        }
                    }
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        func list(json: JSON)->Void {
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    let titles = ["内部人工","人员外包","劳务外包","服务","工程","物资","差旅及其他","合计"]
                    var arr: [JSON] = []
                    for title in titles {
                        for item in data {
                            if item.contents?["name"]?.rawString() == title {
                                arr.append(item)
                            }
                        }
                    }
                    self.secondSectionSource = arr
                    self.tableView.reloadData()
                } else {
                    self.alert(json.contents?["errorMsg"]?.rawString())
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        func income(json: JSON)->Void {
            
            if let data = json.contents?["data"]?.array {
                self.firstSectionSource = data
                self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }
        }
        
        func needReceive(json: JSON)->Void{
            
        }
        
        switch name {
        case "GETORG":
            return org
        case "Total":
            return total
        case "JIIncomes":
            return income
        case "JYYSK":
            return needReceive
        default:
            return list
        }
    }
    
    func popalert() -> Void {
        
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.companyField.text = item.contents?["name"]?.rawString()
                
                self.selectedCompany = item
                
                self.load(with: "Total")
                
                self.load(with: "List")
                
                self.load(with: "JIIncomes")
            }
            alert.addAction(sheet)
        }
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        
        alert.addAction(cancel)
        
        self.present(alert, animated: true, completion: nil)
    }

}
